package model;

import Repository.Repository;
import Repository.RepositoryFactory;
import Repository.UserRepository;
import constants.SMSConstants;

public class AssignRuleSelector implements RuleSelector{
	
	private Repository ruleRepository = RepositoryFactory.getRepository(SMSConstants.RULE);
	private SMSObject smsObject;
	
	public AssignRuleSelector(SMSObject smsObject){
		this.smsObject = smsObject;		
	}
	
	public boolean processRuleRequest()
	{
		
	//System.out.println("Processing Assign Rule Request....");
	Rule assignRule = getRule();
	//System.out.println("Got rule.."+ assignRule);
	return applyRule(assignRule);
	
	}
	
	
	
	public Rule getRule() 
	{
		//This if is for fetching import rules for lead.
		//We pass an SMS Object and check its type and state to find the rule to retrieve
		// This is for fetching assign rules for Lead
			if(smsObject instanceof Lead && smsObject.getCurrentState() instanceof Imported){
				return  (Rule)ruleRepository.retrieve(SMSConstants.LEAD, SMSConstants.ASSIGN);
	}
		return null;
		
	}
	
	private boolean applyRule(Rule rule)
	{
		String criteria = rule.getRuleDescripton();
	//	System.out.println("Applying Assign Rules...");
		if(smsObject instanceof Lead )
		{
			Lead objLead = (Lead)smsObject;
			Repository repository = RepositoryFactory.getRepository(SMSConstants.LEAD);
			if(smsObject.getCurrentState() instanceof Imported) 
			{
				if(criteria.toLowerCase().equals("same city"))
				{	// if city of sales rep is the same as city of the lead
						objLead.setManagedByUser(UserRepository.getSalesRep(objLead.getCity()));
						repository.update(objLead.getSmsObjId(), objLead);
						return true;				
					
			    }
		     }
		} 
		
		return false;
	}
	
	
}
